/**
 * 企业成员管理相关的 React Hooks
 */

import { useState, useCallback, useMemo } from 'react';
import { pingCodeAPI } from '../utils/pingcodeApi';
import type { Member, MemberQueryParams, MemberListResponse, MemberStatistics } from '../types/member';

/**
 * 成员列表管理 Hook
 */
export function useMembers() {
  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [error, setError] = useState<string | null>(null);

  // 获取成员列表
  const fetchMembers = useCallback(async (params?: MemberQueryParams) => {
    setLoading(true);
    setError(null);

    try {
      console.log('获取成员列表，参数:', params);
      
      // 构建查询参数
      const queryParams: Record<string, any> = {};
      
      if (params) {
        if (params.name) queryParams.name = params.name;
        if (params.display_name) queryParams.display_name = params.display_name;
        if (params.email) queryParams.email = params.email;
        if (params.status) queryParams.status = params.status;
        if (params.role) queryParams.role = params.role;
        if (params.department) queryParams.department = params.department;
        if (params.is_admin !== undefined) queryParams.is_admin = params.is_admin;
        if (params.page_index !== undefined) queryParams.page_index = params.page_index;
        if (params.page_size !== undefined) queryParams.page_size = params.page_size;
        if (params.sort_by) queryParams.sort_by = params.sort_by;
        if (params.sort_order) queryParams.sort_order = params.sort_order;
      }

      // 调用API获取用户列表（企业成员）
      const response = await pingCodeAPI.getUsers(queryParams);
      
      console.log('成员列表API响应:', response);

      if (response && response.values) {
        // 转换API响应数据为成员数据格式
        const memberList: Member[] = response.values.map((user: any) => ({
          id: user.id,
          url: user.url,
          name: user.name || user.username || '',
          display_name: user.display_name || user.name || '',
          email: user.email,
          avatar: user.avatar,
          status: user.status === 'enabled' ? 'active' : user.status || 'active', // 转换状态
          role: user.job?.name || user.role, // 提取职位名称
          department: user.department?.name || user.department, // 提取部门名称
          position: user.job?.name || user.position, // 提取职位名称
          phone: user.mobile || user.phone,
          created_at: user.created_at,
          updated_at: user.updated_at,
          last_login_at: user.last_login_at,
          is_admin: user.is_admin || false,
          is_owner: user.is_owner || false,
          permissions: user.permissions || []
        }));

        setMembers(memberList);
        setTotal(response.total || memberList.length);
        
        console.log(`成功获取 ${memberList.length} 个成员，总数: ${response.total || memberList.length}`);
        console.log('API响应分页信息:', {
          page_index: response.page_index,
          page_size: response.page_size,
          total: response.total,
          actual_count: memberList.length
        });
      } else {
        console.warn('API响应格式异常:', response);
        setMembers([]);
        setTotal(0);
      }
    } catch (err) {
      console.error('获取成员列表失败:', err);
      setError(err instanceof Error ? err.message : '获取成员列表失败');
      setMembers([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  }, []);

  // 刷新成员列表
  const refetch = useCallback((params?: MemberQueryParams) => {
    return fetchMembers(params);
  }, [fetchMembers]);

  // 计算成员统计信息
  const statistics = useMemo((): MemberStatistics => {
    const total = members.length;
    const active = members.filter(m => m.status === 'active').length;
    const inactive = members.filter(m => m.status === 'inactive').length;
    const pending = members.filter(m => m.status === 'pending').length;
    const admins = members.filter(m => m.is_admin).length;

    // 按部门统计
    const departmentMap = new Map<string, number>();
    members.forEach(member => {
      const dept = member.department || '未分配';
      departmentMap.set(dept, (departmentMap.get(dept) || 0) + 1);
    });
    const departments = Array.from(departmentMap.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count);

    // 按角色统计
    const roleMap = new Map<string, number>();
    members.forEach(member => {
      const role = member.role || '普通成员';
      roleMap.set(role, (roleMap.get(role) || 0) + 1);
    });
    const roles = Array.from(roleMap.entries())
      .map(([name, count]) => ({ name, count }))
      .sort((a, b) => b.count - a.count);

    return {
      total,
      active,
      inactive,
      pending,
      admins,
      departments,
      roles
    };
  }, [members]);

  return {
    members,
    loading,
    total,
    error,
    statistics,
    fetchMembers,
    refetch
  };
}

/**
 * 成员元数据管理 Hook
 */
export function useMemberMeta() {
  const [departments, setDepartments] = useState<string[]>([]);
  const [roles, setRoles] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // 获取部门列表
  const fetchDepartments = useCallback(async () => {
    try {
      // 这里可以调用专门的部门API，暂时从成员数据中提取
      const response = await pingCodeAPI.getUsers({ page_size: 1000 });
      if (response && response.values) {
        const deptSet = new Set<string>();
        response.values.forEach((user: any) => {
          if (user.department) {
            deptSet.add(user.department);
          }
        });
        setDepartments(Array.from(deptSet).sort());
      }
    } catch (err) {
      console.error('获取部门列表失败:', err);
      setError(err instanceof Error ? err.message : '获取部门列表失败');
    }
  }, []);

  // 获取角色列表
  const fetchRoles = useCallback(async () => {
    try {
      // 这里可以调用专门的角色API，暂时从成员数据中提取
      const response = await pingCodeAPI.getUsers({ page_size: 1000 });
      if (response && response.values) {
        const roleSet = new Set<string>();
        response.values.forEach((user: any) => {
          if (user.role) {
            roleSet.add(user.role);
          }
        });
        setRoles(Array.from(roleSet).sort());
      }
    } catch (err) {
      console.error('获取角色列表失败:', err);
      setError(err instanceof Error ? err.message : '获取角色列表失败');
    }
  }, []);

  // 获取所有元数据
  const fetchMeta = useCallback(async () => {
    setLoading(true);
    setError(null);

    try {
      await Promise.all([
        fetchDepartments(),
        fetchRoles()
      ]);
    } catch (err) {
      console.error('获取成员元数据失败:', err);
      setError(err instanceof Error ? err.message : '获取成员元数据失败');
    } finally {
      setLoading(false);
    }
  }, [fetchDepartments, fetchRoles]);

  return {
    departments,
    roles,
    loading,
    error,
    fetchDepartments,
    fetchRoles,
    fetchMeta
  };
}